package org.manager.properties;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.manager.generic.Repository.GenericHibernateRepository;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Repository;

@SuppressWarnings("unchecked")
@Repository("propertiesRepository")
public class PropertiesRepositoryImpl extends GenericHibernateRepository<Properties> implements PropertiesRepository {

	public List<Properties> page(final Properties pro,final int start,final int limit) {
		return (List)getHibernateTemplate().execute(new HibernateCallback(){
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				return session.createCriteria(Properties.class)
					.add(Example.create(pro))
					.setFirstResult(start*limit)
					.setMaxResults(limit).list();
			}
		});
	}
	
	
	public int totalRecord(final Properties pro) {
		return (Integer)getHibernateTemplate().execute(new HibernateCallback(){
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				return session.createCriteria(Properties.class)
					.add(Example.create(pro))
					.setProjection(Projections.rowCount()).uniqueResult();
			}
		});
	}
	
	
	
	public Serializable addProperties(final Properties pro) {
		//添加的时候需要将节点上一级的code和本级code相加: 1.1
		String parentCode = "";
		
		if(StringUtils.isNotBlank(pro.getParentId())){
			//查询父参数.获得父参数的code.
			Properties parent = (Properties)getHibernateTemplate().execute(new HibernateCallback(){
				public Object doInHibernate(Session session)
						throws HibernateException, SQLException {
					List l = session.createCriteria(Properties.class).add(Restrictions.eq("id", pro.getParentId())).list();
					if(l != null && l.size() > 0){
						return l.get(0);
					}
					return null;
				}
			});
			if(parent == null) return null;
			parentCode = parent.getCode()+".";
			if(StringUtils.isBlank(parentCode)) return null;
			pro.setParentCode(parent.getCode());
		}
		
			
			//查询本级参数中,最小的code.
			List<Properties> propertiesList = getHibernateTemplate().executeFind(new HibernateCallback(){
				public Object doInHibernate(Session session)
						throws HibernateException, SQLException {
					Criterion c;
					if(StringUtils.isBlank(pro.getParentId())){
						c = Restrictions.isNull("parentId");
					}else{
						c = Restrictions.eq("parentId", pro.getParentId());
					}
					return session.createCriteria(Properties.class).add(c).list();
				}
			});
			
			int maxCode = 0;
			for(Properties p : propertiesList){
				String code = p.getCode();
				if(code != null && code.lastIndexOf(".") > -1){
					code = code.substring(code.lastIndexOf(".")+1, code.length());
				}
				if(NumberUtils.isNumber(code) && NumberUtils.toInt(code)>maxCode){
					maxCode = NumberUtils.toInt(code);
				}
			}
			
			pro.setCode(parentCode+(maxCode+1));
		
		return save(pro);
	}
	
	
	
	public boolean checkBusinessCode(final Properties pro) {
		return (Boolean)getHibernateTemplate().execute(new HibernateCallback(){
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Criterion c;
				if(StringUtils.isBlank(pro.getParentId())){
					c = Restrictions.isNull("parentId");
				}else{
					c = Restrictions.eq("parentId", pro.getParentId());
				}
				List l = session.createCriteria(Properties.class)
				.add(c).add(Restrictions.eq("businessCode", pro.getBusinessCode())).list();
				if(l == null || l.size() <= 0){
					l = null;
					return true;
				}else{
					l = null;
					return false;
				}
			}
		});
	}
	
	
	@Override
	public List<Properties> selectByParent(final String parentId) {
		return (List<Properties>)getHibernateTemplate().execute(new HibernateCallback(){
			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Properties parent = (Properties)session.load(Properties.class, parentId);
				Iterator it = parent.getChildren().iterator();
				return iterator2List(it);
			}
		});
	}
	
	
	@Override
	public List<Properties> selectByProperty(final String propertyId) {
		return (List<Properties>) getHibernateTemplate().execute(new HibernateCallback(){
			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Property property = (Property)session.load(Property.class, propertyId);
				return iterator2List(property.getPropertiesSet().iterator());
			}
		});
	}
	
	
	private List<Properties> iterator2List(Iterator it){
		List<Properties> childList = new ArrayList<Properties>();
		if(it != null){
			while(it.hasNext()){
				Properties p = (Properties)it.next();
				Properties node = new Properties();
				/*if(p.getChildren().size() < 1){
					continue;
				}*/
				node.setId(p.getId());
				node.setName(p.getName());
				node.setCode(p.getCode());
				node.setEnglishName(p.getEnglishName());
				childList.add(node);
			}
		}
		return childList;
	}

}
